package com.goodlearning.gloriamobile.net;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;

import com.goodlearning.gloriamobile.commons.Constants;
import com.goodlearning.gloriamobile.commons.Utils;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
/**
 * WebService 전면 요청 공통 정의 
 * @author rapty54
 *
 */
public class JsonRequestThread extends Thread{
	
	public interface INetSuccessCallback {
		public void sendCallback(JsonWrapper jsonWrapper);
	}

	public interface INetFailCallback {
		public void sendCallback();
	}

	/*public interface IJsonNetCallback {
		public void sendCallback(JsonWrapper jsonWrapper);
	}*/
	
	
	private Context context;
	private String serviceName;
	private Map<String, String> paramMap;
	private INetSuccessCallback successCallback;
	private INetFailCallback failCallback;
	private ProgressDialog prgDlg; 
	private CallbackHandler callbackHandler = new CallbackHandler();
	
	//private static final String surl = "http://112.216.159.170:4003/";			//테스트 
	private static final String url_activated ="https://cyber.gloriahrd.com/";  /// 요청 Protocol https 로 접근해야 한다. ㅡㅡ;
	private static final String surl = "http://192.168.11.148:8019/";			//실서버
	
	
	public JsonRequestThread(Context context, String serviceName, Map<String, String> paramMap, INetSuccessCallback successCallback, INetFailCallback failCallback, ProgressDialog prgDlg) {
		this.context = context;
		this.serviceName = serviceName;
		this.paramMap = paramMap;
		this.successCallback = successCallback;
		this.failCallback = failCallback;
		this.prgDlg = prgDlg;
	}

	@Override
	public void run() {
		Utils.log( "-------------------------------------------------------------------------- Start Request ------------------------------------------------------------------");
		URL url = null;
		HttpURLConnection conn = null;
		PrintWriter pw = null;
		BufferedReader br = null;
		
		try {
			
			url = new URL(url_activated+serviceName);
			conn = (HttpURLConnection) url.openConnection();

			if (conn != null) {
				
				//연결설정
				conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded;charset=utf-8");
				conn.setDoInput(true);
				conn.setDoOutput(true);
				conn.setUseCaches(false);
				conn.setRequestMethod("POST");
				conn.setConnectTimeout(10000);
				conn.setAllowUserInteraction(true);
				conn.setInstanceFollowRedirects(false);
				
				Utils.log("Request Cookie------------------------------------------------------------------");
				Utils.log(Utils.convertObjToString(Constants.cookie));
				
				//받아놓은 세션정보가 관련 cookie가 있다면 Header에 추가
				if(Constants.cookie !=null){
					conn.addRequestProperty("cookie", Constants.cookie);
				}
				
				//파라미터 세팅
				StringBuffer paramSb = new StringBuffer();
				Utils.log( "Request Url---------------------------------------------------------------------");
				if(paramMap != null){
					Iterator<String> keyIt = paramMap.keySet().iterator();
					int cnt = 0;
					while (keyIt.hasNext()) {
						String key = keyIt.next();
						String value = paramMap.get(key);
						if(value != null){
							if(0 < cnt){
								paramSb.append("&");
							}
							paramSb.append(URLEncoder.encode(key, "utf8") + "=" + URLEncoder.encode(value, "utf8"));
						}
						cnt++;
					}
					Utils.log( url_activated+serviceName+paramSb.toString());
				}
				
				//요청돌입
				pw = new PrintWriter(new OutputStreamWriter(conn.getOutputStream()));
				pw.write(paramSb.toString());   
				pw.flush();
				
				//응답헤더정보 출력
				Utils.log( "Response Header -----------------------------------------------------");
				Iterator<String> it = conn.getHeaderFields().keySet().iterator();
				while (it.hasNext()) {
					String key = it.next();
					Utils.log( key + " : "+conn.getHeaderField(key));
				}
				
				//응답처리
				int responseCode = conn.getResponseCode();
				
				if (responseCode == HttpURLConnection.HTTP_OK) {
					//응답성공
					Utils.log( "ResponseOK   - HttpURLConnection.HTTP_OK -----------------------------------------------------");
					if(/*Constants.cookie == null && */conn.getHeaderField("set-cookie") != null){
						Constants.cookie = conn.getHeaderField("set-cookie");
					}
					
					////프로그레스바가 닫혔다면 이는 의도적인 경우이므로 다음 작업을 무시하고 콜백을 호출하지않는다.
					if(prgDlg != null){
						if( ! prgDlg.isShowing() ){
							return;
						}
					}
					
					/*Constants.cookie = conn.getHeaderField("set-cookie");
					XmlPullParser xml = XmlPullParserFactory.newInstance().newPullParser();
					xml.setInput(conn.getInputStream(), "utf8");
					XmlWrapper xmlWrapper = new XmlWrapper(xml);
					Message msg = new Message();
					msg.what = 0;
					msg.obj = xmlWrapper;
					callbackHandler.sendMessage(msg);*/
					
					
					
					//응답 BodyData출력
					/*StringBuffer responseSb = new StringBuffer();
					String line;
					br = new BufferedReader( new InputStreamReader( conn.getInputStream() , "utf-8" ) );
					while((line = br.readLine()) != null){
						responseSb.append(line);
					}
					Utils.showLog( "Response OK! ------------------ Body data-----------------------------------------------------");
					Utils.showLog( responseSb.toString());*/
					
					JsonWrapper jsonWrapper = new JsonWrapper( new BufferedReader( new InputStreamReader( conn.getInputStream() , "utf-8" ) ) );
					Message msg = new Message();
					msg.what = 0;
					msg.obj = jsonWrapper;
					callbackHandler.sendMessage(msg);
					
				} else{
					//응답실패
					if(/*Constants.cookie == null &&*/ conn.getHeaderField("set-cookie") != null){
						Constants.cookie = conn.getHeaderField("set-cookie");
					}
					
					Utils.log( "ResponseError-----------------------------------------------------");
					Utils.log( "HTTP ResponseCode : "+responseCode );
					callbackHandler.sendEmptyMessage(1);
					
					//
					/*StringBuffer errLogSb = new StringBuffer();
					String line;
					br = new BufferedReader( new InputStreamReader( conn.getErrorStream() , "utf-8" ) );
					while((line = br.readLine()) != null){
						errLogSb.append(line);
					}
					Utils.showLog( "ResponseError-----------------------------------------------------");
					Utils.showLog( "HTTP ResponseCode : "+responseCode );
					Utils.showLog( conn.getResponseMessage());
					String[] errLogs = errLogSb.toString().split("<");
					for (int i = 0; i < errLogs.length; i++) {
						Utils.showLog(errLogs[i] );
					}*/
					
				}

			}

		} catch (Exception e) {
			Utils.ePrintStackTrace(e);
			Message msg= new Message();
			msg.obj = e.getMessage();
			msg.what=2;
			callbackHandler.sendMessage(msg);
		} finally {
			
			try {
				if(pw != null){
					pw.close();
				}
				if(br != null){
					br.close();
				}
				if(conn != null){
					conn.disconnect();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		}
		
	}
	
	public class CallbackHandler extends Handler{
		
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			
			try {
				//프로그레스바가 닫혔다면 이는 의도적인 경우이므로 다음 작업을 무시하고 콜백을 호출하지않는다.
				if(prgDlg != null){
					if( ! prgDlg.isShowing() ){
						return;
					}
				}
				
				if(msg.what == 0 ){
					//응답성공
					if(msg.obj != null && successCallback != null ){  
						JsonWrapper json = (JsonWrapper) msg.obj;
						successCallback.sendCallback(json);
						
					}else if(failCallback != null){
						failCallback.sendCallback();
						
					}else{
						//Utils.showNetNoticeDialog(context, "응답없음", "서버의 응답이 없습니다.", null, null);
						Utils.showNetNoticeDialog(context, "네트워크 오류", "데이터 수신에 문제가 있어 올바르지 않은 정보가 노출될 수 있습니다. 네트워크 환경을 확인하세요.", null, null);
						
					}
					
				}else{
					
					if(failCallback != null){
						failCallback.sendCallback();
						
					}else if(msg.what == 1 ){
						//응답실패
						//Utils.showNetNoticeDialog(context, "서비스 실패", "서비스 요청에 실패하였습니다.", null, null);
						Utils.showNetNoticeDialog(context, "네트워크 오류", "데이터 수신에 문제가 있어 올바르지 않은 정보가 노출될 수 있습니다. 네트워크 환경을 확인하세요.", null, null);
						
					}else /*if(msg.what == 2 )*/{
						//예외발생
						//Utils.showNetNoticeDialog(context, "예외발생", "메시지 : "+msg.obj, null, null);
						Utils.showNetNoticeDialog(context, "네트워크 오류", "데이터 수신에 문제가 있어 올바르지 않은 정보가 노출될 수 있습니다. 네트워크 환경을 확인하세요.", null, null);
					}
				}
					
				
			} catch (Exception e) {
				Utils.ePrintStackTrace(e);
			}finally{
				if(prgDlg != null){
					try {
						prgDlg.dismiss();
					} catch (Exception e) {
						// TODO: handle exception
					}
					
				}
			}
			
		}
	}
	
}